import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
import { Modal } from "bootstrap";
export default {
    name: "Car",
    data() {
        return {
            carInfo: [],
            searchValue: '',
            newCar: {
                name: '',
                type: '',
                brand: '',
                newlevel: '',
                optype: '1',
            },
            carToAssignCoach: {},
            selectedCoachId: '',
        };
    },
    created: function() {
        this.fetchCars();
    },

    methods: {
        //显示车辆信息
        async fetchCars() {
            try {
                const url = "http://localhost:8081/car/list";
                const response = await axios.get(url);

                this.carInfo = response.data.data.map(car => {
                    const imagePath = car.image ? car.image.replace(/^D:.*image/, '/image') : '/path/to/default/image.png';
                    return {
                        ...car,
                        image : imagePath,
                    };
                });
            } catch (error) {
                console.error("Fetching cars error:", error);
            }
        },
        // 添加新车辆
        async addCar() {
            try {
                const url = "http://localhost:8081/car/add";

                const response = await axios.post(url, this.newCar);
                if (response.data.code === 20000) {
                    const addCarModal = Modal.getInstance(document.getElementById("addCarModal"));
                    addCarModal.hide();
                    this.resetNewCarData();
                    this.$message.success("添加车辆成功！");
                    this.fetchCars();
                } else {
                    this.$message.error("Adding car failed:", response.data.message);
                }
            } catch (error) {
                console.error("Adding car error:", error);
            }
        },


        // 重置添加车辆模态框的数据
        resetNewCarData() {
            this.newCar = {
                name: '',
                type: '',
                brand: '',
                newlevel: '',
                optype: '',
            };
        },
        // 删除车辆
        async deleteCar(car) {
            try {
                if (confirm("确认删除该车辆？")) {
                    const url = `http://localhost:8081/car/delete/${car.id}`;
                    const response = await axios.delete(url);

                    if (response.data.code === 20000) {
                        this.fetchCars();
                        this.$message.success("删除车辆成功！");
                    } else {
                        this.$message.error(`删除车辆失败：${response.data.message}`);
                    }
                }
            } catch (error) {
                console.error("Deleting car error:", error);
            }
        },
        // 保存编辑后的车辆信息
        async saveEditedCar(car) {
            try {
                const url = `http://localhost:8081/car/update/${car.id}`;
                const response = await axios.put(url, car);

                if (response.data.code === 20000) {
                    this.fetchCars();
                    this.$message.success("编辑车辆成功！");
                    car.editing = false;
                } else {
                    this.$message.error(`编辑车辆失败：${response.data.message}`);
                }
            } catch (error) {
                console.error("Saving edited car error:", error);
            }
        },
        // 上传车辆图片
        getComputedID(car) {
            return `upload-image-btn-${car.id}`;
        },
        //上传图片
        async handleFileUpload(event, car) {
            try {
                const file = event.target.files[0];

                const formData = new FormData();
                formData.append("image", file);

                const url = `http://localhost:8081/car/uploadImage/${car.id}`;
                const response = await axios.post(url, formData, {
                    headers: {
                        "Content-Type": "multipart/form-data",
                    },
                });

                if (response.data.code === 20000) {
                    car.image = response.data.data.image;
                    this.fetchCars();
                    this.$message.success("上传图片成功！");
                } else {
                    this.$message.error(`上传图片失败：${response.data.message}`);
                }
            } catch (error) {
                console.error("Uploading image error:", error);
            }
        },
        //查询车辆
        async search() {
            try {
                const url = `http://localhost:8081/car/search/${this.searchValue}`;
                const response = await axios.get(url);

                if (response.data.code === 20000) {
                    const imagePath = response.data.data.image.replace(/^D:.*image/, '/image');
                    this.carInfo = [
                        {
                            ...response.data.data,
                            image: imagePath,
                        },
                    ];
                    this.searchValue = '';
                    this.$message.success("查询成功！");
                } else {
                    this.searchValue = '';
                    this.$message.error(`查询出错：${response.data.message}`);
                }
            } catch (error) {
                console.error("Searching error:", error);
                alert("搜索车辆出错，请检查输入的ID和网络连接。");
            }
        },

        setCarToAssignCoach(car) {
            this.carToAssignCoach = car;
            const assignCoachModal = new Modal(document.getElementById('assignCoachModal'), {});
            assignCoachModal.show();
        },
        //分配教练
        async assignCoach() {
            // 从这里调用 API，并为车辆分配教练：

            try {
                const url = `http://localhost:8081/car/arrange/${this.carToAssignCoach.id}`;
                const response = await axios.post(url, null, {
                    params: {
                        coach: this.selectedCoachId
                    }
                });

                if (response.data.code === 20000) {
                    this.$message.success("车辆分配成功！");
                }
                else {
                    this.$message.error("车辆分配失败:", response.data.message);
                }
                this.selectedCoachId = '';
            } catch (error) {
                this.selectedCoachId = '';
                this.$message.error("车辆分配失败!");
            }

            // 关闭模态框
            const assignCoachModal = Modal.getInstance(document.getElementById('assignCoachModal'));
            assignCoachModal.hide();
        },
    },
};